<?php

namespace Beerus\Modules\CategoryEntrance\Controllers;

use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\ShopCategoryClassify as mShopCategoryClassify;
use Biz\service\admin\CategoryWikiCard as sCategoryWikiCard;
use Biz\service\esSearch\Wiki as esWiki;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CategoryWikiControllerCard extends Controller
{
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content)
    {
        $page = $request->input('page', 1);
        $limit = [
            ($page - 1) * self::PAGE_SIZE,
            self::PAGE_SIZE
        ];

        return $content->header('好物分类feed插入wiki商品')
            ->breadcrumb(
                ['text' => '好物分类feed插入wiki商品']
            )->row($this->grid($request->all(), $limit));
    }

    public function update(Request $request)
    {
        try {
            $params = $request->all();

            if (!is_numeric($params['wiki_id'])) {
                throw new InputErrorException('wiki_id只能输入数字', InputErrorException::DEFAULT_CODE, 'wiki_id');
            }

            if (!is_numeric($params['category_id'])) {
                throw new InputErrorException('category_id只能输入数字', InputErrorException::DEFAULT_CODE, 'category_id');
            }

            if ($params['start_time'] >= $params['end_time']) {
                throw new InputErrorException('开始时间必须小于结束时间', InputErrorException::DEFAULT_CODE, 'start_time');
            }

            sCategoryWikiCard::update($params, Admin::user()->id);

            $success = new MessageBag([
                'title' => '保存成功'
            ]);

            return redirect('/admin/categoryEntrance/categorywikilist')->with(compact('success'));

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function delete($id = 0)
    {
        $result = sCategoryWikiCard::delete($id);
        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
    }

    public function create(Content $content)
    {
        $form = new Form([]);
        $form->text('brand_id', '品牌ID')->required();
        $form->text('brand_name', '品牌名称')->readonly()->placeholder('输入品牌ID显示品牌名称');
        $form->text('wiki_id', 'wiki商品id')->required();
        $form->text('title', '标题')->readonly()->placeholder('输入wikiID显示wiki名称');
        $form->select('category_id', '分类ID')->required()->options($this->getCategoryList());
        $form->select('insert_position', '展示位置')->required()->options(range(1, 10));
        $form->datetime('start_time', '开始时间')->required();
        $form->datetime('end_time', '结束时间')->required();
        $form->action('/admin/categoryEntrance/categorywikilist/update');
        Admin::script($this->getBaseInfoScript());
        return $content->header('编辑白名单')
            ->breadcrumb(
                ['text' => '广告曝光套餐白名单管理', 'url' => 'categoryEntrance/categorywikilist'],
                ['text' => '编辑白名单']
            )
            ->row($form);
    }

    private function grid($params, $limit)
    {
        $where = $this->buildWhere($params);
        $list = sCategoryWikiCard::getList($where, $limit);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        return Admin::grid($gridModel, function (Grid $grid) {

            $grid->filter(function ($filter) {
                $filter->disableIdFilter();

                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('category_id', '分类ID')->placeholder('分类ID');
                    $filter->equal('brand_id', '品牌ID')->placeholder('品牌ID');
                });


                $filter->column(1 / 2, function ($filter) {
                    $filter->dropDown('time', [
                        'time' => '展示时间',
                    ])->betweenDatetime();
                });

                $filter->column(1 / 2, function ($filter) {
                    $filter->dropDown('wiki_value', [
                        'wiki_id' => '商品id',
                        'title' => '商品名称',
                    ]);
                });

                $filter->expand();//默认展开
            });

            $grid->column('id', 'ID');
            $grid->column('brand_id', '品牌id');
            $grid->column('brand_name', '品牌名称');
            $grid->column('wiki_id', '商品id');
            $grid->column('title', '商品名称');
            $grid->column('category_id', '分类ID');
            $grid->column('classify_name', '分类名称');
            $grid->column('insert_position', '展示位置');
            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');

            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
            });
        });
    }

    private function buildWhere($params = [])
    {
        $where['card_status'] = 1;
        if ($params['category_id']) {
            $where['category_id'] = $params['category_id'];
        }

        if ($params['brand_id']) {
            $where['brand_id'] = $params['brand_id'];
        }

        if ($params['time']['start']) {
            $where['start_time[>=]'] = $params['time']['start'];
        }

        if ($params['time']['end']) {
            $where['end_time[<=]'] = $params['time']['end'];
        }

        if (isset($params['wiki_id']) && $params['wiki_id']) {
            $where['wiki_id'] = $params['wiki_id'];
        } elseif (isset($params['title']) && $params['title']) {
            $result = esWiki::getList($params['wiki_id'], esWiki::SCENES_SHOP_ADMIN_CATEGORY_WIKI_CARD);
            if ($result['rows']) {
                $where['wiki_id'] = $result['rows'];
            }
        }

        return $where;
    }

    private function getCategoryList()
    {
        $category = [];
        $list = mShopCategoryClassify::getList(['deep' => mShopCategoryClassify::DEEP_FIRST_CLASSIFY, 'status' => mShopCategoryClassify::STATUS_NORMAL]);

        foreach ($list as $info) {
            $category[$info['id']] = $info['classify_name'];
        }

        return $category;
    }

    public function getBasicInfo(Request $request)
    {
        $objType = $request->input('type');
        if ($objType == 'wiki') {
            $objId = $request->input('wiki_id');
        } else if ($objType == 'brand') {
            $objId = $request->input('brand_id');
        }
        $result = sCategoryWikiCard::getBasicInfo($objType, $objId);
        return [
            'code' => 1,
            'msg' => $result
        ];
    }

    public function getBaseInfoScript()
    {
        return <<<EOF
$('.brand_id').blur(function(){
    var shop_id = $(this).val();
    var url = 'getbasicinfo?brand_id=' + $(this).val() + '&type=brand'
    $.get(url, function (result) {
        if (result.code == 1) {
            $('.brand_name').val(result.msg)
        }
    });  
})

$('.wiki_id').blur(function(){
    var wiki_id = $(this).val();
    var url = 'getbasicinfo?wiki_id=' + $(this).val() + '&type=wiki'
    $.get(url, function (result) {
        if (result.code == 1) {
            $('.title').val(result.msg)
        }
    });  
})
EOF;
    }
}